const connection = require('../app/database')

class UserSevice {
    async create (user) {
        const { username, password, gender, birthday, contact, avatar } = user
        console.log('d',avatar)
        const avatarBuffer = Buffer.from(avatar, 'base64')
        const statement = `INSERT INTO users (username, password, gender, birthday, contact, avatar) VALUES(?, ?, ?, ?, ?, ?);`;
        // const statement = `INSERT INTO user (name, password) VALUES(?, ?);`;
        try {
            const result = await connection.execute(statement, [username, password, gender, birthday, contact, avatarBuffer])
            console.log('first')

            return result
        } catch (error) {
            console.log('error', error)
        }

        // 将用户信息存储到数据库中
    }
    // 
    async getUserByName(username) {
        const statement = `SELECT * FROM users WHERE username = ?;`
        const result = await connection.execute(statement, [username])
        // 只有第一个才是查询的字段
        return result[0]
    }

    // 更新用户信息
    async updateUserInfo(filed, palyload, id, username) {
        const statement = `UPDATE users SET ${filed} = ? WHERE id = ?;`;
        const result = await connection.execute(statement, [palyload, id])
        return this.getUserByName(username)
    }

    // 更新用户全部信息
    async updateInfo(id, columns, statement) {
        console.log('2')
        try {
            const result = await connection.execute(statement)
            return result[0]
        } catch (error) {
            console.log('error', error)
        }
        
    }

    async getUserDetail(userId) {
        try {
            const statement = `SELECT u.id, u.username,u.avatar, u.gender, u.birthday, u.desc, u.contact, u.reg_time, 
            COUNT(DISTINCT d.id) AS article_count,
            COUNT(DISTINCT f.id) AS following_count,
            COUNT(DISTINCT f2.id) AS follower_count
          FROM 
            users u 
            LEFT JOIN posts d ON u.id = d.user_id 
            LEFT JOIN follow f ON u.id = f.followerId 
            LEFT JOIN follow f2 ON u.id = f2.followedId 
              WHERE u.id = ?
          GROUP BY  u.id;`;
            const result = await connection.execute(statement, [userId])
            return result[0]
        } catch (error) {
            console.log('err',error)
        }
        
    }
}

module.exports = new UserSevice()